package de.slothsoft.commons.swing.window;

import java.awt.Window;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import de.slothsoft.commons.swing.AbstractListTableModel;
import de.slothsoft.commons.swing.ITableCreator;
import de.slothsoft.commons.swing.ITableHolder;
import de.slothsoft.commons.swing.SlothsoftTableCellRenderer;
import de.slothsoft.commons.swing.TableCreatorUtil;
import de.slothsoft.commons.swing.util.JTableUtil;

public abstract class AbstractTableDialog<T> extends AbstractDialog implements
		ITableHolder<T>, ITableCreator<T> {

	// TODO: abstract for filter, reset

	private static final long serialVersionUID = 1L;

	protected AbstractListTableModel<T> model;
	protected JTable table;

	public AbstractTableDialog(Window parent) {
		this(parent, ButtonType.OK, ButtonType.CANCEL);
	}

	public AbstractTableDialog(Window parent, ButtonType... buttonTypes) {
		super(parent, buttonTypes);
		updateButtonEnablement();
	}

	@Override
	@SuppressWarnings("unchecked")
	protected void createMainPanel(JPanel mainPanel) {
		this.table = TableCreatorUtil.buildTable(this, mainPanel);
		this.model = (AbstractListTableModel<T>) this.table.getModel();
	}

	@Override
	public TableCellRenderer createRenderer() {
		return new SlothsoftTableCellRenderer();
	}

	@Override
	public int[] createColumnWidths() {
		return null;
	}

	@Override
	public JComponent createFilterComponent() {
		return null;
	}

	@Override
	public JComponent createInformationComponent() {
		return null;
	}

	@Override
	public void performSelectionChanged() {
		updateButtonEnablement();
	}

	protected void updateButtonEnablement() {
		JButton okButton = getButton(ButtonType.OK);
		if (okButton == null) {
			return;
		}
		okButton.setEnabled(this.table.getSelectedRow() != -1);
	}

	@Override
	public void performDoubleClick() {
		performOkAction();
	}

	@Override
	public void refresh() {
		this.model.fireTableDataChanged();
	}

	@Override
	public JTable getTable() {
		return this.table;
	}

	@Override
	public AbstractListTableModel<T> getModel() {
		return this.model;
	}

	@Override
	public T getSelectedElement() {
		return JTableUtil.getSelectedElement(this.table, this.model);
	}

	@Override
	public List<T> getSelectedElements() {
		return JTableUtil.getSelectedElements(this.table, this.model);
	}

	@Override
	protected void performOkAction() {
		super.performOkAction();
		close();
	}

}
